package com.teaching.management.controller;

import com.teaching.management.entity.Course;
import com.teaching.management.entity.Teacher;
import com.teaching.management.entity.User;
import com.teaching.management.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import jakarta.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

/**
 * 教师控制器
 */
@Controller
@RequestMapping("/teacher")
public class TeacherController {

    @Autowired
    private TeacherService teacherService;

    /**
     * 显示教师仪表盘
     */
    @GetMapping("/dashboard")
    public String showDashboard(Model model, HttpSession session) {
        // 检查用户是否登录
        User user = (User) session.getAttribute("user");
        if (user == null || !"教师".equals(user.getRole())) {
            return "/login";
        }

        // 获取教师信息
        Teacher teacher = teacherService.getTeacherByUserId(user.getUserId());
        if (teacher == null) {
            return "/login";
        }

        // 获取教学概览数据
        Map<String, Object> overview = teacherService.getTeachingOverview(teacher.getTeacherId());
        model.addAttribute("overview", overview);

        // 获取教师课程
        List<Course> courses = teacherService.getTeacherCourses(teacher.getTeacherId());
        model.addAttribute("courses", courses);

        model.addAttribute("teacher", teacher);

        return "teacher/dashboard";
    }

    /**
     * 我的课程页面
     */
    @GetMapping("/courses")
    public String showCourses(Model model, HttpSession session) {
        // 检查用户是否登录
        User user = (User) session.getAttribute("user");
        if (user == null || !"教师".equals(user.getRole())) {
            return "/login";
        }

        // 获取教师信息
        Teacher teacher = teacherService.getTeacherByUserId(user.getUserId());
        if (teacher == null) {
            return "/login";
        }

        // 获取教师课程
        List<Course> courses = teacherService.getTeacherCourses(teacher.getTeacherId());
        model.addAttribute("courses", courses);

        return "teacher/courses";
    }

    /**
     * 课程详情页面
     */
    @GetMapping("/course/{courseId}")
    public String showCourseDetail(@PathVariable String courseId, Model model, HttpSession session) {
        // 检查用户是否登录
        User user = (User) session.getAttribute("user");
        if (user == null || !"教师".equals(user.getRole())) {
            return "/login";
        }

        // 获取教师信息
        Teacher teacher = teacherService.getTeacherByUserId(user.getUserId());
        if (teacher == null) {
            return "/login";
        }

        // 获取课程详情
        Course course = teacherService.getCourseById(courseId);
        if (course == null) {
            return "redirect:/teacher/courses";
        }

        // 检查课程是否属于该教师
        if (!course.getTeacherId().equals(teacher.getTeacherId())) {
            return "redirect:/teacher/courses";
        }

        // 获取课程的学生数量
        int studentCount = teacherService.getStudentCountForCourse(courseId);
        course.setStudentCount(studentCount);

        model.addAttribute("course", course);
        model.addAttribute("teacher", teacher);

        return "teacher/course-detail";
    }

    /**
     * 我的学生页面
     */
    @GetMapping("/students")
    public String showStudents(Model model, HttpSession session) {

        // 检查用户是否登录
        User user = (User) session.getAttribute("user");
        if (user == null || !"教师".equals(user.getRole())) {
            return "/login";
        }

        // 获取教师信息
        Teacher teacher = teacherService.getTeacherByUserId(user.getUserId());
        if (teacher == null) {
            return "/login";
        }

        // 获取该教师所有课程的学生
        List<Map<String, Object>> students = teacherService.getTeacherStudents(teacher.getTeacherId());
        model.addAttribute("students", students);

        // 获取教师课程列表用于筛选
        List<Course> courses = teacherService.getTeacherCourses(teacher.getTeacherId());
        model.addAttribute("courses", courses);

        return "teacher/students";
    }

    /**
     * 成绩管理页面
     */
    @GetMapping("/grades")
    public String showGrades(Model model, HttpSession session) {
        // 检查用户是否登录
        User user = (User) session.getAttribute("user");
        if (user == null || !"教师".equals(user.getRole())) {
            return "/login";
        }

        // 获取教师信息
        Teacher teacher = teacherService.getTeacherByUserId(user.getUserId());
        if (teacher == null) {
            return "/login";
        }

        // 获取该教师所有课程的成绩记录
        List<Map<String, Object>> grades = teacherService.getTeacherGrades(teacher.getTeacherId());
        model.addAttribute("grades", grades);

        // 获取教师课程列表用于筛选
        List<Course> courses = teacherService.getTeacherCourses(teacher.getTeacherId());
        model.addAttribute("courses", courses);

        return "teacher/grades";
    }

    /**
     * 个人信息页面
     */
    @GetMapping("/profile")
    public String showProfile(Model model, HttpSession session) {
        // 检查用户是否登录
        User user = (User) session.getAttribute("user");
        if (user == null || !"教师".equals(user.getRole())) {
            return "/login";
        }

        // 获取教师信息
        Teacher teacher = teacherService.getTeacherByUserId(user.getUserId());
        if (teacher == null) {
            return "/login";
        }

        // 获取教学概览数据
        Map<String, Object> overview = teacherService.getTeachingOverview(teacher.getTeacherId());

        // 设置教师课程和学生数量
        teacher.setCourseCount((Integer) overview.get("courseCount"));
        teacher.setStudentCount((Integer) overview.get("studentCount"));

        model.addAttribute("teacher", teacher);

        return "teacher/profile";
    }

    /**
     * 课程编辑页面
     */
    @GetMapping("/course/{courseId}/edit")
    public String showCourseEditForm(@PathVariable String courseId, Model model, HttpSession session) {
        // 检查用户是否登录
        User user = (User) session.getAttribute("user");
        if (user == null || !"教师".equals(user.getRole())) {
            return "/login";
        }

        // 获取教师信息
        Teacher teacher = teacherService.getTeacherByUserId(user.getUserId());
        if (teacher == null) {
            return "/login";
        }

        // 获取课程详情
        Course course = teacherService.getCourseById(courseId);
        if (course == null) {
            return "redirect:/teacher/courses";
        }

        // 检查课程是否属于该教师
        if (!course.getTeacherId().equals(teacher.getTeacherId())) {
            return "redirect:/teacher/courses";
        }

        model.addAttribute("course", course);
        model.addAttribute("teacher", teacher);

        return "teacher/course-edit";
    }

    /**
     * 处理课程编辑提交
     */
    @PostMapping("/course/{courseId}/update")
    public String updateCourse(@PathVariable String courseId, Course updatedCourse, HttpSession session) {
        // 检查用户是否登录
        User user = (User) session.getAttribute("user");
        if (user == null || !"教师".equals(user.getRole())) {
            return "/login";
        }

        // 获取教师信息
        Teacher teacher = teacherService.getTeacherByUserId(user.getUserId());
        if (teacher == null) {
            return "/login";
        }

        // 获取课程详情
        Course existingCourse = teacherService.getCourseById(courseId);
        if (existingCourse == null) {
            return "redirect:/teacher/courses";
        }

        // 检查课程是否属于该教师
        if (!existingCourse.getTeacherId().equals(teacher.getTeacherId())) {
            return "redirect:/teacher/courses";
        }

        // 更新课程信息
        boolean success = teacherService.updateCourse(courseId, updatedCourse);
        if (!success) {
            // 处理更新失败情况
            return "redirect:/teacher/course/" + courseId + "/edit?error=1";
        }

        return "redirect:/teacher/course/" + courseId + "?updated=1";
    }

    /**
     * 处理课程删除请求
     */
    @PostMapping("/course/{courseId}/delete")
    public String deleteCourse(@PathVariable String courseId, HttpSession session) {
        // 检查用户是否登录
        User user = (User) session.getAttribute("user");
        if (user == null || !"教师".equals(user.getRole())) {
            return "/login";
        }

        // 获取教师信息
        Teacher teacher = teacherService.getTeacherByUserId(user.getUserId());
        if (teacher == null) {
            return "/login";
        }

        // 获取课程详情
        Course course = teacherService.getCourseById(courseId);
        if (course == null) {
            return "redirect:/teacher/courses";
        }

        // 检查课程是否属于该教师
        if (!course.getTeacherId().equals(teacher.getTeacherId())) {
            return "redirect:/teacher/courses";
        }

        // 删除课程
        boolean success = teacherService.deleteCourse(courseId);
        if (!success) {
            // 处理删除失败情况
            return "redirect:/teacher/course/" + courseId + "?error=delete";
        }

        return "redirect:/teacher/courses?deleted=1";
    }

    /**
     * 学生详情页面
     */
    @GetMapping("/student/{studentId}")
    public String showStudentDetail(@PathVariable String studentId, Model model, HttpSession session) {
        // 检查用户是否登录
        User user = (User) session.getAttribute("user");
        if (user == null || !"教师".equals(user.getRole())) {
            return "/login";
        }

        // 获取教师信息
        Teacher teacher = teacherService.getTeacherByUserId(user.getUserId());
        if (teacher == null) {
            return "/login";
        }

        // 获取学生详情和选课信息
        Map<String, Object> studentDetail = teacherService.getStudentDetail(studentId, teacher.getTeacherId());
        if (studentDetail == null) {
            return "redirect:/teacher/students?error=student-not-found";
        }

        model.addAttribute("student", studentDetail.get("student"));
        model.addAttribute("courses", studentDetail.get("courses"));
        model.addAttribute("teacher", teacher);

        return "teacher/student-detail";
    }

    /**
     * 学生课程成绩管理页面
     */
    @GetMapping("/course/{courseId}/student/{studentId}/grade")
    public String showStudentCourseGrade(
            @PathVariable String courseId,
            @PathVariable String studentId,
            Model model,
            HttpSession session) {
        // 检查用户是否登录
        User user = (User) session.getAttribute("user");
        if (user == null || !"教师".equals(user.getRole())) {
            return "/login";
        }

        // 获取教师信息
        Teacher teacher = teacherService.getTeacherByUserId(user.getUserId());
        if (teacher == null) {
            return "/login";
        }

        // 获取课程详情
        Course course = teacherService.getCourseById(courseId);
        if (course == null || !course.getTeacherId().equals(teacher.getTeacherId())) {
            return "redirect:/teacher/courses";
        }

        // 获取学生选课记录
        Map<String, Object> gradeInfo = teacherService.getStudentCourseGrade(studentId, courseId);
        if (gradeInfo == null) {
            return "redirect:/teacher/student/" + studentId + "?error=course-not-found";
        }

        model.addAttribute("course", course);
        model.addAttribute("student", gradeInfo.get("student"));
        model.addAttribute("selection", gradeInfo.get("selection"));
        model.addAttribute("teacher", teacher);

        return "teacher/student-grade";
    }
}